$(function () {
  initArtList();

  function initArtList() {
    axios({
      method: "GET",
      url: "/my/article/cates",
    }).then((res) => {
      if (res.data.status !== 0) {
        return layui.layer.msg(res.data.message);
      }
      let arr = ['<option value="">请选择文章分类</option>'];
      res.data.data.forEach((ele) => {
        arr.push(`
                    <option value=${ele.Id}>${ele.name}</option>
                `);
      });
      let str = arr.join("");
      $("[name=cate_id]").empty().html(str);
      layui.form.render();
    });
  }
  initEditor();
  var $image = $("#image");

  // 2. 裁剪选项
  var options = {
    aspectRatio: 400 / 280,
    preview: ".img-preview",
  };

  let state = "";
  $("#btn1").on("click", function () {
    state = "已发布";
  });
  $("#btn2").on("click", function () {
    state = "草稿";
  });
  $("#CBtn").on("click", function () {
    $("#CImg").click();
  });
  $("#CImg").on("change", function (e) {
    var file = e.target.files[0];
    if (!file) {
      return layer.msg("不能为空！");
    }
    var newImgURL = URL.createObjectURL(file);
    $image
      .cropper("destroy") // 销毁旧的裁剪区域
      .attr("src", newImgURL) // 重新设置图片路径
      .cropper(options);
  });
  $image.cropper(options);
  $("#formPub").on("submit", function (e) {
    e.preventDefault();
    let fd = new FormData(this);
    fd.append("state", state);
    $image
      .cropper("getCroppedCanvas", {
        // 创建一个 Canvas 画布
        width: 400,
        height: 280,
      })
      .toBlob(function (blob) {
        // 将 Canvas 画布上的内容，转化为文件对象
        // 得到文件对象后，进行后续的操作
        fd.append("cover_img", blob);
        axios({
          method: "POST",
          url: "/my/article/add",
          data: fd,
        }).then((res) => {
          if (res.data.status !== 0) {
            return layui.layer.msg(res.data.message);
          }
          layui.layer.msg("成功");
          setInterval(function () {
            // location.href = "./list.html";
            window.parent.document.querySelector("#List").click();
          }, 2000);
        });
      });
  });
});
